package ru.chaykin.measures;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

import ru.chaykin.graphdrawers.Pen;
import ru.chaykin.primitives.Point;


public class Area extends Measure {

	private static final int MAX_SIZE = 128;
	
	private Pen linesPen;
	private Pen lastLinesPen;
	private FloatBuffer lastLine;

	public Area(Pen linesPen, Pen lastLinesPen, float radius) {
		this.linesPen=linesPen;
		this.lastLinesPen=lastLinesPen;
		this.radius = radius;
		startSize = radius;
		ByteBuffer bb = ByteBuffer.allocateDirect(12 * MAX_SIZE);	//Максимальное число точек полигона - 128
		bb.order(ByteOrder.nativeOrder());
		linesBuff = bb.asFloatBuffer();
		ByteBuffer lbb = ByteBuffer.allocateDirect(12 * 2);	//Максимальное число точек полигона - 128
		lbb.order(ByteOrder.nativeOrder());
		lastLine = lbb.asFloatBuffer();
	}
	
	public void draw(GL10 gl) {
		if (linesBuff != null) {	//Словил NullPointerException. Вызвано неправильным порядком вызова обработчиков
			linesPen.applayToScene(gl);
			gl.glVertexPointer(3, GL10.GL_FLOAT, 0, linesBuff);
			gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, size);
			for (int i = 0; i < size; i++) {
				gl.glVertexPointer(3, GL10.GL_FLOAT, 0, marksBuffs.get(i));
				gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, ANGLES);
			}
			lastLinesPen.applayToScene(gl);
			gl.glVertexPointer(3, GL10.GL_FLOAT, 0, lastLine);
			gl.glDrawArrays(GL10.GL_LINES, 0, 2);
		}
	}

	public void add(Point p) {
		if (size < MAX_SIZE) {
			linesBuff.position(3 * size);
			linesBuff.put(p.getx());
			linesBuff.put(p.gety());
			linesBuff.put(Point.z);
			linesBuff.position(0);
			initMarksBuff();
			buildCircle(size, p, radius);
			if (size > 1) {
				lastLine.clear();
				lastLine.put(linesBuff.get(0));
				lastLine.put(linesBuff.get(1));
				lastLine.put(linesBuff.get(2));
				lastLine.put(linesBuff.get(3 * size));
				lastLine.put(linesBuff.get(3 * size + 1));
				lastLine.put(linesBuff.get(3 * size + 2));
				lastLine.position(0);
			}
			size++;
		}
		else {
			linesBuff.clear();
			marksBuffs.clear();
			add(p); //Типа рекурсия...
		}
	}

	public String getMeasuredData() {
		if (size >= 3) {
			float s = 0;
			for (int i = 0; i < 3 * size; i += 3) {
				if (i == 3 * size - 3)
					s += (linesBuff.get(0) - linesBuff.get(i)) * (linesBuff.get(1) + linesBuff.get(i + 1)) / 2f;
				else
					s += (linesBuff.get(i + 3) - linesBuff.get(i)) * (linesBuff.get(i + 4) + linesBuff.get(i + 1)) / 2f;
			}
			int fS = Math.abs((int) (s * 100f));
			return fS / 100.0 + "";
		}		
		return "";
	}
}
